package com.mpsc.spring.demo.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 事件监听一步线程池
 * https://blog.csdn.net/Beijing_L/article/details/122587211
 */
@EnableAsync
@Configuration
@ComponentScan("com.mpsc.spring.demo.event")
public class EventConfig {
    //核心线程数（默认线程数）
    private static final int corePoolSize = 10;
    //最大线程数
    private static final int maxPoolSize = 100;
    //允许线程空闲时间（默认为妙）
    private static final int keepAliveTime = 10;
    //缓冲队列数
    private static final int queueCapacity = 200;
    //线程池名前缀
    private static final String threadNamePreFix = "Async-Service-";

    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setThreadNamePrefix(threadNamePreFix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    /**
     * 创建线程池执行程序（事件监听无关）
     *
     */
    @Bean(name = "executorService")
    public ExecutorService downloadExecutorService() {
        return new ThreadPoolExecutor(20, 40, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2000),
                new ThreadFactoryBuilder().setNameFormat("defaultExecutorService-%d").build(),
                (r, executor) -> System.out.println("defaultExecutor pool is full! "));
    }
}
